package gogo

import (
	"os"
	"os/exec"
	"strconv"
	"strings"
)

func service(handler func(), err_handle func(err error)) {

	restart_delay := 0
	var args []string

	for i := 1; i < len(os.Args); i++ {
		if strings.HasPrefix(os.Args[i], "--gogo-restart-delay") {
			restart_delay, _ = strconv.Atoi(strings.Split(os.Args[i], "=")[1])
			continue
		}
		args = append(args, os.Args[i])
	}

	if restart_delay > 0 {
		for {
			cmd := exec.Command(os.Args[0], args...)
			cmd.Env = os.Environ()
			//cmd.Stdin = os.Stdin
			cmd.Stdout = os.Stdout
			cmd.Stderr = os.Stderr

			var err error

			if err = cmd.Start(); err != nil {
				Log().ErrorF("failed to run command: %v\n", err)
			} else if err = cmd.Wait(); err != nil {
				Log().ErrorF("failed to wait command: %v\n", err)
			}

			err_handle(err)

			Utils().TimeSleepMilliSecond(restart_delay)
		}
	}

	handler()
}

func GuardStart(proc_handler func(), err_handle func(err error)) {
	daemon := false
	var args []string

	for i := 1; i < len(os.Args); i++ {
		if os.Args[i] == "--gogo-background" {
			daemon = true
			continue
		}
		args = append(args, os.Args[i])
	}

	if daemon {
		cmd := exec.Command(os.Args[0], args...)
		cmd.Stdout = os.Stdout //把cmd的输出指向标准输出,不然控制台看不到
		cmd.Stderr = os.Stderr //把cmd的错误输出指向标准错误输出,不然控制台看不到
		cmd.Env = os.Environ()
		if err := cmd.Start(); err != nil {
			Log().ErrorF("failed to run command: %s\n", err)
			err_handle(err)
		}
		return
	}

	service(proc_handler, err_handle)
}
